package weixinkeji.dev.dc.buy.control;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import sys.wx.m.db.SQL.mysql.common.orderby.OrderBy;
import sys.wx.m.db.dao.mysql.Dao;
import weixinkeji.dev.dc.buy.order.bean.FWYOrder;

/**
 *
 * @author imyweb
 */
public class OrderCodeService {

    private static int i = 1;
    private static String date;
    private static int today;

    static {

        newDate(LocalDate.now());

    }

    /**
     * 获得订单的号
     *
     * @return
     */
    synchronized public static String getOrderCode() {
        LocalDate now = LocalDate.now();
        return now.getDayOfMonth() == today
                ? date + new DecimalFormat("0000").format(i++)
                : newDate(now) + new DecimalFormat("0000").format(i++);
    }

    /**
     * 新的一天。重置时间与流水号
     *
     * @param ld
     * @return
     */
    private static String newDate(LocalDate ld) {
        date = ld.format(DateTimeFormatter.ofPattern("yyyyMMdd"));//;("yyyy-MM-dd")
        today = ld.getDayOfMonth();

        List<FWYOrder> s = Dao.selectVastOrderBy(FWYOrder.class, 1, 1, OrderBy.getOrderBy("order_code", "DESC"));
        if (s.size() > 0) {
            FWYOrder obj = s.get(0);
            obj.getOrder_code();
            int orderDate = Integer.parseInt(obj.getOrder_code().substring(6, 8));
            i = today == orderDate ? (Integer.parseInt(obj.getOrder_code().substring(8)) + 1) : 1;
        } else {
            i = 1;
        }

        return date;
    }

}
